package com.hcc.repository.gen.engine.impl;

import com.hcc.repository.gen.engine.TemplateEngine;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Freemarker模板引擎
 *
 * @author hushengjun
 * @date 2023/9/18
 */
public class FreemarkerTemplateEngine implements TemplateEngine {

    private final Configuration configuration;

    public FreemarkerTemplateEngine() {
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
        configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, "/");
    }

    @Override
    public void generateFile(Map<String, Object> dataModel, String templatePath, File targetFile) {
        try (FileOutputStream fileOutputStream = new FileOutputStream(targetFile)) {
            Template template = configuration.getTemplate(templatePath);
            template.process(dataModel, new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException(String.format("freemarker模板：[%s]转换异常", templatePath), e);
        }
    }

}
